package com.fz.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.fz.controller.dto.LoginDTO;
import com.fz.controller.request.BaseRequest;
import com.fz.controller.request.LoginRequest;
import com.fz.controller.request.PasswordRequest;
import com.fz.exception.ServiceException;
import com.fz.mapper.AdminMapper;
import com.fz.mapper.UserMapper;
import com.fz.pojo.Admin;
import com.fz.pojo.User;
import com.fz.service.AdminService;
import com.fz.service.UserService;
import com.fz.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

@Service
@Slf4j
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    //    管理员默认密码
    private static final String DEFAULT_PASSWORD = "123";
    //加密 密码加盐法
    private static final String PASSWORD_SALT = "fangzheng";

    @Override
    public List<Admin> list() {
        return adminMapper.list();
    }

    //分页
    @Override
    public PageInfo<Admin> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize());
        List<Admin> admins = adminMapper.listByCondition(baseRequest);
        return new PageInfo<>(admins);
    }

    //添加管理员
    @Override
    public void addAdmin(Admin admin) {
        //返回值为空设置默认密码
        if (StrUtil.isBlank(admin.getPassword())) {
            //    管理员默认密码
            admin.setPassword(DEFAULT_PASSWORD);
        }
        //md5加密 加盐fangzheng
        admin.setPassword(securePassword(admin.getPassword()));

        try {
            adminMapper.addAdmin(admin);
        } catch (Exception e){
            log.error("数据插入失败：username：{}"+admin.getUsername(),e);
            throw new ServiceException("用户名重复");
        }

    }

    //通过id查询用户
    @Override
    public Admin getById(Integer id) {
        return adminMapper.getById(id);


    }

    @Override
    public void update(Admin admin) {
        admin.setUpdateTime(new Date());
        adminMapper.updateById(admin);
    }

    @Override
    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    //登录
    @Override
    public LoginDTO login(LoginRequest loginRequest) {
        //前端传入明文密码，对密码 md5密码加密加盐 返回后端数据库查询
//        loginRequest.setPassword(securePassword(loginRequest.getPassword()));
        Admin admin = null;
        try {
            admin = adminMapper.getByUsername(loginRequest.getUsername());
        } catch (Exception e) {
            log.error("根据用户名{} 查询出错", loginRequest.getUsername());
            throw new ServiceException("用户名错误");
        }

        if (admin == null) {
            throw new ServiceException("用户名或密码错误");
        }
        //判断密码是否合法
        //前端传入明文密码，对密码 md5密码加密加盐 返回后端数据库查询
        String securePassword = securePassword(loginRequest.getPassword());
        if (!securePassword.equals(admin.getPassword())) {
            throw new ServiceException("用户名或密码错误");
        }

        if (!admin.isStatus()) {
            throw new ServiceException("当前用户处于禁用状态：请联系管理员");
        }

        LoginDTO loginDTO = new LoginDTO();
        BeanUtils.copyProperties(admin, loginDTO);//复制属性 返回

        //生成token
        String token = TokenUtils.genToken(String.valueOf(admin.getId()), admin.getPassword());
        loginDTO.setToken(token);
        return loginDTO;


    }

    //修改管理员密码
    @Override
    public void updatePassword(PasswordRequest passwordRequest) {
        //对新密码加密
        passwordRequest.setNewPassword(securePassword(passwordRequest.getNewPassword()));
        int count = adminMapper.updatePassword(passwordRequest);
        if (count <= 0) {
            throw new ServiceException("修改密码失败");
        }


    }

    //前端传入明文密码，对密码 md5密码加密加盐 返回后端数据库查询
    private String securePassword(String password) {
        return SecureUtil.md5(password + PASSWORD_SALT);
    }
}
